import re
from typing_extensions import ParamSpec
from flask import Flask
from flask import Flask,request,jsonify
import json
from flask_cors import CORS
from config import Config
from db import db1
app = Flask(__name__)
CORS(app)
# app.config.from_object(Config)

@app.route('/cate',methods=['POST','GET'])
def cate():
    # 添加分类
    if request.method=='POST':
        data = request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        sql = "insert into cate values(0,'%s')"%(data['name'])
        db1.insert(sql)
        return jsonify({'code':200})
        # 获取分类
    elif request.method=='GET':
        sql = "select * from cate"
        res= db1.findall(sql)
        return jsonify({'code':200,'list':res})

@app.route('/good',methods=['POST','GET','DELETE'])
def good():
    # 添加商品
    if request.method=='POST':
        data = request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        sql = "insert into goods values(0,'%s','%s')"%(data['name'],data['cate'])
        db1.insert(sql)
        return jsonify({'code':200})
    # 获取商品
    elif request.method=='GET':
        uid = int(request.args.get('uid'))
        if uid>0:
            cate = request.args.get('cate')
            sql = "select * from goods where cate='%s'"%(cate)
            res= db1.findall(sql)
        else:
            sql = "select * from goods order by id desc"
            res= db1.findall(sql)
        return jsonify({'code':200,'list':res})

    # 删除商品
    elif request.method=='DELETE':
        id = request.args.get('id')
        sql = "delete from goods where id=%d"%(int(id))
        db1.insert(sql)
        return jsonify({'code':200})

if __name__ == '__main__':
    app.run(debug=True)